package com.sskj.cndragon.ui.activity;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.Group;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.previewlibrary.GPreviewBuilder;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.cndragon.R;
import com.sskj.cndragon.bean.ImgBean;
import com.sskj.cndragon.bean.LastTimeBean;
import com.sskj.cndragon.bean.OrderBuyListBean;
import com.sskj.cndragon.http.HttpConfig;
import com.sskj.cndragon.presenter.OrderSellDetailActivityPresenter;
import com.sskj.cndragon.view.ToolBarLayout;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.util.CopyUtil;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;


public class OrderSellDetailActivity extends BaseActivity<OrderSellDetailActivityPresenter> {
    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.tv_buyer_name)
    TextView tvBuyerName;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R.id.tv_dragon_name)
    TextView tvDragonName;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.tv_dragon_type)
    TextView tvDragonType;
    @BindView(R.id.tv_days)
    TextView tvDays;
    @BindView(R.id.tv_incomes)
    TextView tvIncomes;
    @BindView(R.id.tv_deal_money)
    TextView tvDealMoney;
    @BindView(R.id.tv_phoenix_money)
    TextView tv_phoenix_money;
    @BindView(R.id.tv_seller_name1)
    TextView tvSellerName1;
    @BindView(R.id.tv_seller_mobile)
    TextView tvSellerMobile;
    @BindView(R.id.tv_buyer_name1)
    TextView tv_buyer_name1;
    @BindView(R.id.tv_msg)
    TextView tv_msg;
    @BindView(R.id.iv_copy)
    ImageView ivCopy;
    @BindView(R.id.iv_pay_img)
    ImageView ivPayImg;
    @BindView(R.id.tv_count_down)
    TextView tvCountDown;
    @BindView(R.id.tv_confirm_count_down)
    TextView tv_confirm_count_down;
    @BindView(R.id.btn_confirm_pay)
    Button btnConfirmPay;
    @BindView(R.id.btn_shensu)
    Button btnShensu;
    @BindView(R.id.group)
    Group group;
    @BindView(R.id.group_pay_count_down)
    Group group_pay_count_down;
    @BindView(R.id.group_confirm_count_down)
    Group group_confirm_count_down;
    @BindView(R.id.group_btns)
    Group group_btns;

    private String orderID;
    private String pollID;
    private String mOrderID;

    private long createTime;
    private long endtime;


    private List<ImgBean> localMedia = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_order_sell_detail;
    }

    @Override
    public OrderSellDetailActivityPresenter getPresenter() {
        return new OrderSellDetailActivityPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        toolbar.setLeftButtonOnClickListener(view -> finish());
        ClickUtil.click(300, btnConfirmPay, () -> {
            if (isEmpty(mOrderID)) {
                return;
            }
            mPresenter.confirmPay(mOrderID);
        });
        ClickUtil.click(300, ivPayImg, () -> {
            GPreviewBuilder.from(OrderSellDetailActivity.this)//activity实例必须
                    .setData(localMedia)//集合
                    .setCurrentIndex(0)
                    .setSingleFling(false)//是否在黑屏区域点击返回
                    .setDrag(false)//是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Dot)//指示器类型
                    .start();//启动
        });
        ClickUtil.click(300, ivCopy, new ClickUtil.Click() {
            @Override
            public void click() {
                if (isEmpty(getText(tvSellerMobile))) {
                    return;
                }
                CopyUtil.copy(getText(tvSellerMobile));
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        pollID = getIntent().getStringExtra(Constans.POLL_ID);
        orderID = getIntent().getStringExtra(Constans.ORDER_ID);

        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                if (!isEmpty(pollID) && !isEmpty(orderID)) {
                    mPresenter.getSellDetailMsg(pollID, orderID, coolRefreshView);
                }
                if (localMedia != null) {
                    localMedia.clear();
                }
            }
        });

        if (!isEmpty(pollID) && !isEmpty(orderID)) {
            mPresenter.getSellDetailMsg(pollID, orderID, null);
        }
    }

    public static void start(Context context, String pollID, String orderID) {
        Intent intent = new Intent(context, OrderSellDetailActivity.class);
        intent.putExtra(Constans.POLL_ID, pollID);
        intent.putExtra(Constans.ORDER_ID, orderID);
        context.startActivity(intent);
    }

    public void getSellDetailMsgOK(OrderBuyListBean.OrderBuyBean data) {
        if (data == null) {
            return;
        }
        List<String> payTypes = Arrays.asList(getResources().getStringArray(R.array.lib_recharges_types));
        //申诉
        ClickUtil.click(300, btnShensu, () ->
        {
            TipUtil.orderAppeal(OrderSellDetailActivity.this, payTypes, string ->
                    mPresenter.shensu(data.getSellStockUserId()
                            , data.getBuyStockUserId()
                            , data.getSwiftNo()
                            , string
                            , data.getId()));
        });
        mOrderID = data.getId();
        createTime = data.getCreateTime();
        tvBuyerName.setText(data.getBuyUsername());
        tvSellerName1.setText(data.getBuyUsername());
        tv_buyer_name1.setText(data.getBuyUsername() + "将于");
        tvDragonName.setText(data.getName());
        tvOrder.setText(data.getSwiftNo());
        tvOrderStatus.setText(data.getStatus() == 1 ? App.INSTANCE.getString(R.string.appDaifukuan) :
                data.getStatus() == 2 ? App.INSTANCE.getString(R.string.appFukaunzhong) :
                        data.getStatus() == 3 ? App.INSTANCE.getString(R.string.appFukuanchenggong) :
                                data.getStatus() == 4 ? App.INSTANCE.getString(R.string.appYiwancheng) :
                                        data.getStatus() == 5 ? App.INSTANCE.getString(R.string.appShensuzhong) :
                                                data.getStatus() == 6 ? App.INSTANCE.getString(R.string.appYiquxiao) : "");
        tvDragonType.setText(data.getName());
        tvDays.setText(data.getContractDays());
        tvIncomes.setText(NumberUtil.keepNoZero(data.getProfitRatio()) + "%");
        tvDealMoney.setText("￥" + NumberUtil.keep2(data.getPrice()));
        tv_phoenix_money.setText(NumberUtil.keep2(data.getPhoenixPrice()) + "FHB");
        tvSellerMobile.setText(data.getBuyTel());
        if (data.getStatus() == 1 || data.getStatus() == 2) {//买家待付款
            tv_msg.setVisibility(View.VISIBLE);
            group_pay_count_down.setVisibility(View.VISIBLE);//倒计时
            group_confirm_count_down.setVisibility(View.GONE);//倒计时
            group_btns.setVisibility(View.GONE);//确认 申诉按钮
            group.setVisibility(View.GONE);//付款图片
            mPresenter.getLastTime(Constans.BUY);
        } else if (data.getStatus() == 3) {//卖家待确认
            tv_msg.setVisibility(View.VISIBLE);
            group_pay_count_down.setVisibility(View.GONE);
            group_confirm_count_down.setVisibility(View.VISIBLE);
            group_btns.setVisibility(View.VISIBLE);
            group.setVisibility(View.VISIBLE);
            mPresenter.getLastTime(Constans.SELL);
            localMedia.add(new ImgBean(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl()));
            ImageUtil.setImage(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl(), ivPayImg);
        } else if (data.getStatus() == 4) {//订单已完成
            tv_msg.setVisibility(View.VISIBLE);
            group_confirm_count_down.setVisibility(View.GONE);
            group_btns.setVisibility(View.GONE);
            group.setVisibility(View.VISIBLE);
            localMedia.add(new ImgBean(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl()));
            ImageUtil.setImage(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl(), ivPayImg);
        } else if (data.getStatus() == 5) {//订单申诉中
            tv_msg.setVisibility(View.VISIBLE);
            group_confirm_count_down.setVisibility(View.GONE);
            group_btns.setVisibility(View.GONE);
            group.setVisibility(View.VISIBLE);
            localMedia.add(new ImgBean(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl()));
            ImageUtil.setImage(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl(), ivPayImg);
        } else if (data.getStatus() == 6) {//订单已取消
            tv_msg.setVisibility(View.VISIBLE);
            group_confirm_count_down.setVisibility(View.GONE);
            group_btns.setVisibility(View.GONE);
            if (isEmpty(data.getPayImgUrl())) {
                group.setVisibility(View.GONE);
            } else {
                group.setVisibility(View.VISIBLE);
                localMedia.add(new ImgBean(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl()));
                ImageUtil.setImage(data.getPayImgUrl().contains("http") ? data.getPayImgUrl() : HttpConfig.BASE_URL + data.getPayImgUrl(), ivPayImg);
            }
        }
    }

    public void getLastTimeOK(LastTimeBean data, int countType) {
        if (data == null) {
            return;
        }
        if (countType == Constans.BUY) {
            endtime = createTime / 1000 + Long.valueOf(data.getPay_time()) * 60;
            long nowTime = System.currentTimeMillis() / 1000;
            if (endtime - nowTime > 0) {
                startTimeDown(endtime - nowTime, tvCountDown);
            }
        } else if (countType == Constans.SELL) {
            endtime = createTime / 1000 + Long.valueOf(data.getConfirm_time()) * 60;
            long nowTime = System.currentTimeMillis() / 1000;
            if (endtime - nowTime > 0) {
                startTimeDown(endtime - nowTime, tv_confirm_count_down);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposableSubscriber != null) {
            if (!disposableSubscriber.isDisposed()) {
                disposableSubscriber.dispose();
                disposableSubscriber = null;
            }
        }
    }

    protected DisposableSubscriber<Long> disposableSubscriber;

    public void startTimeDown(Long totalLong, TextView textView) {
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                long time = (int) (totalLong - aLong);
                if (textView != null) {
                    textView.setText(TimeFormatUtil.parseTime(time));
                }
                if (time == 1) {
                    mPresenter.getSellDetailMsg(pollID, orderID, null);
                    if (localMedia != null) {
                        localMedia.clear();
                    }
                }
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                if (disposableSubscriber != null) {
                    if (!disposableSubscriber.isDisposed()) {
                        disposableSubscriber.dispose();
                        disposableSubscriber = null;
                    }
                }

            }
        };

        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(totalLong)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    public void confirmOK() {
        mPresenter.getSellDetailMsg(pollID, orderID, null);
    }
}
